package kamikaze.service.product;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import kamikaze.entity.Product;
import kamikaze.support.HttpMethod;
import kamikaze.support.Service;
import kamikaze.support.ServiceConfig;
import kamikaze.support.ServiceContext;
import kamikaze.support.ServiceException;

@ServiceConfig(path = "product.create.action", method = HttpMethod.POST)
public class CreateProductService implements Service {

	@Override
	public String serve(ServiceContext ctx) throws Exception {
		
		ctx.getUserSession().ensureLoginAsUser();

		HttpServletRequest req = ctx.getRequest();
		final Product product = new Product();

		product.setCategory(req.getParameter("prodCat"));
		product.setName(req.getParameter("prodName"));
		product.setPicture(req.getParameter("prodPicture"));

		BigDecimal price = BigDecimal.ZERO;
		String strPrice = req.getParameter("prodPrice");
		if (strPrice != null && !strPrice.isEmpty()) {
			strPrice = strPrice.replaceAll(",", "");
			Double dprice = Double.parseDouble(strPrice);
			price = BigDecimal.valueOf(dprice);
		}
		product.setPrice(price);
		product.setComment(req.getParameter("sellerComment"));
		product.setProductId(System.currentTimeMillis());
		product.setCreatedDate(new Date());
		product.setOwnerKey(ctx.getUserSession().asUser().getId());
		product.setOwnerName(ctx.getUserSession().asUser().getName());

		List<String> errors = product.validate();

		if (!errors.isEmpty()) {
			throw new ServiceException(errors.toString());
		}

		ctx.getEntityManager().persist(product);

		return "redirect:/service/product/list";
	}
}
